<template>
  <el-dialog
    :title="isEdit ? '编辑' : '新增'"
    width="60%"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
    :close-on-click-modal="false"
  >
    <div>
      <el-form
        ref="formRef"
        :model="formValues"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="通知标题" prop="title">
          <el-input
            v-model="formValues.title"
            maxlength="100"
            show-word-limit
            placeholder="请输入"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="通知类型" prop="messageType">
              <el-select
                v-model="formValues.messageType"
                placeholder="请选择"
                class="w-[100%]"
              >
                <el-option
                  v-for="item in options['message_type']"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="接收人员">
              <VCascader
                v-model="formValues.receiver"
                collapse-tags
                collapse-tags-tooltip
                class="w-[100%]"
                placeholder="默认全员,可修改指定部门接受"
                @treeId="getTreeIds"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="发布方式">
              <el-radio-group v-model="formValues.sendType">
                <el-radio
                  :label="item.value"
                  v-for="item in options['send_type']"
                  :key="item"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="发布时间"
              v-if="formValues.sendType == 2"
              prop="sendTime"
            >
              <el-date-picker
                v-model="formValues.sendTime"
                type="datetime"
                placeholder="请选择"
                class="w-full"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="通知方式">
              <el-select
                v-model="formValues.noticeType"
                placeholder="请选择"
                class="w-[100%]"
              >
                <el-option
                  v-for="item in options['notice_type']"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="弹窗等级"
              prop="popLevel"
              v-if="formValues.noticeType == 3"
            >
              <el-select
                v-model="formValues.popLevel"
                placeholder="请选择"
                class="w-[100%]"
              >
                <el-option
                  v-for="item in options['pop_level']"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否同步飞书">
          <el-radio-group v-model="formValues.isSyncFeishu">
            <el-radio
              :label="item.value"
              v-for="item in options?.['bool']"
              :key="item"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <WangEditor v-model="formValues.content" class="w-full" />
        </el-form-item>
        <el-form-item>
          <Upload v-model="formValues.file" :limit="10" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import WangEditor from "@/components/WangEditor/index.vue";
import { messageAdd, messageEdit, messageDetails } from "../../api.js";
import { getCurrentFormattedTime } from "@/utils/time.js";
import Upload from "../Upload/index";
import {processHtmlImage} from '../../data'
const props = defineProps({
  id: { type: [Number, String], default: null },
  modelValue: { type: Boolean, default: false },
  // title: { type: String, default: "新增" },
  disabled: { type: Boolean, default: false },
  options: { type: Object, default: () => ({}) },
});
const loading = ref(false);
const { options } = toRefs(props);
const emit = defineEmits(["update:modelValue", "refresh", "close"]);
const formValues = ref({
  id: null,
  title: null,
  messageType: null,
  receiver: null,
  sendTime: null,
  noticeType: null,
  popLevel: null,
  content: null,
  isSyncFeishu: 1,
  sendType: 1,
  file: [],
});
const isEdit = computed(() => !!props.id);
watch(
  () => props.id,
  async (val) => {
    if (val) {
      getDetail();
    }
  }
);
const getDetail = async () => {
  try {
    loading.value = true;
    const { data } = await messageDetails({ id: props.id });
    Object.keys(formValues.value).forEach((key) => {
      formValues.value[key] = data[key]?.value ?? data[key];
    });
    if(!data?.file){
      formValues.value.file = []
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
const rules = reactive({
  title: [{ required: true, message: "通知标题不能为空", trigger: "blur" }],
  messageType: [
    { required: true, message: "通知类型不能为空", trigger: "blur" },
  ],
  sendTime: [{ required: true, message: "发布时间不能为空", trigger: "blur" }],
  popLevel: [{ required: true, message: "弹窗等级不能为空", trigger: "blur" }],
  content: [{ required: true, message: "通知内容不能为空", trigger: "blur" }],
});
const formRef = ref();
const receiverAll = ref([]);
const getTreeIds = (val) => {
  receiverAll.value = val || [];
};
const handleSave = async () => {
  try {
    loading.value = true;
    formRef.value?.validate(async (valid) => {
      if (valid) {
        if (formValues.value.sendType == 1) {
          formValues.value.sendTime = getCurrentFormattedTime();
        }
        if (!formValues.value?.receiver) {
          formValues.value.receiver = receiverAll.value;
        }
        if(formValues.value?.content){
          let con = await processHtmlImage(formValues.value?.content)
          formValues.value.content = con
        }
        const { code, message } = await (isEdit.value
          ? messageEdit
          : messageAdd)(formValues.value);
        if (code !== 200) return ElMessage.error(message);
        ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
        handleClose(true);
      } else {
        return false;
      }
    });
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};
const handleClose = async (refresh) => {
  formValues.value = {
    id: null,
    title: null,
    messageType: null,
    receiver: null,
    sendTime: null,
    noticeType: null,
    popLevel: null,
    content: null,
    isSyncFeishu: 1,
    sendType: 1,
    file: [],
  };
  await nextTick();
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
